/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


package edu.ut.ece382c.valloy.ui;


import java.io.BufferedWriter;
import javax.swing.JFileChooser;
import java.io.FileWriter;
import java.io.FilenameFilter;

import edu.mit.csail.sdg.alloy4whole.*;
import edu.ut.ece382c.valloy.translator.engine.ParserTranslator;

//RMV
import java.io.*;


class VLSFileFilter extends javax.swing.filechooser.FileFilter {
    public boolean accept(File f) {
        return f.isDirectory() || f.getName().toLowerCase().endsWith(".vls");
    }

    public String getDescription() {
        return ".vls files";
    }
}

class AlloyFileFilter extends javax.swing.filechooser.FileFilter {
    public boolean accept(File f) {
        return f.isDirectory() || f.getName().toLowerCase().endsWith(".vls");
    }

    public String getDescription() {
        return ".als files";
    }
}

/**
 * ValloyInputController: Use this class to pass all the
 * inputs from a GUI Interface, or any commands other
 * input commands to the ValloyConverter.  You will then call the ValloyParser
 * to implement the business logic of the Parser.
 * You may think of this as an input tester.  At the end we may only need
 * one simple command execution.
 * @author vasr
 */
public class ValloyInputController {

    SimpleGUI asguiParent;
    
    ValloyParser _valloyParser = null;

    String _OpenedFileName = "";
    String _ErrorData = "";
    String _DefaultTransferFileName = "c:\\alloy_data_temp.als";
    Boolean ValloyFilehasChanged = false;

    File _CurrentDirValloyFilePath;
    File _CurrentDirAlloyFilePath;

    
    public ValloyInputController()
    {
    
    }
    
    public ValloyInputController(SimpleGUI pParent)
    {
        asguiParent = pParent;
    }

    public String CurrentFileName()
    {
        return _OpenedFileName;
    }

    public String ErrorData()
    {
        return _ErrorData;
    }
    
    
    //TODO:
    //RV NOtes: Replace with code that
    //1- Extracts the Class Hierarchy and put it into a file, or a
    //JTextArea.  I need to figure out how it can be sent directly
    //to an alloy window and the format we may need.  For now we need the business
    //logic to the parsing.
    public  void ExtractClassHierarchy(javax.swing.JTextArea AlloyTextArea)
    {
//       try{
//            // Open the file that is the first
//            // command line parameter
//            String _FileName = "C:\\UT Classes\\Source Code\\ValloyAlloyConverter\\Data\\FunctionData.txt";
//            File openAs = new File(_FileName);
//            FileReader in = new FileReader(openAs);
//            AlloyTextArea.read(in, openAs.toString());
//        }
//        catch(java.io.IOException ex){
//                System.out.println("Cannot read from file");
//        }
        if ( CanRunStringParser()){
         AlloyTextArea.setText(_valloyParser.ParseClassHierarchy());
        }
    }


    //String Parser extracts Alloy Functions
    public  void GenerateAlloyFunctions(javax.swing.JTextArea AlloyTextArea)
    {
        if ( CanRunStringParser()){
         AlloyTextArea.setText(_valloyParser.ParseFunctions());
        }
       
    }

    //String Parser extracts Alloy Functions
    public  void GenerateAlloyPredicates(javax.swing.JTextArea AlloyTextArea)
    {
        if ( CanRunStringParser()){
         AlloyTextArea.setText(_valloyParser.ParsePredicates());
        }

    }

    //String Parser extracts Alloy Classes and Functions
    public  void ParseClassesAndFunctions(javax.swing.JTextArea AlloyTextArea)
    {
        if ( CanRunStringParser()){
         AlloyTextArea.setText(_valloyParser.ParseClassesFunctions());
        }

    }

    //String Parser extracts Non-Alloy Data
    public  void ExtractNonConvertedData(javax.swing.JTextArea AlloyTextArea)
    {
        if ( CanRunStringParser()){
         AlloyTextArea.setText(_valloyParser.NonConvertedData());
        }

    }

    //String Parser extracts Alloy Functions
    //THIS IS TO CONNECT TO THE LEXER PARSER.
    public  void ExecuterLexerParser(javax.swing.JTextArea AlloyTextArea)
    {
        if (_OpenedFileName.length() > 0){
        	ParserTranslator parser = new ParserTranslator();
        	File model = new File (_OpenedFileName);
        	try {
        		AlloyTextArea.setText(parser.TranslateModule(model));
        	}
        	catch (Exception exc){
        		AlloyTextArea.setText(exc.toString());
        	}
        }	

    }

    //StringParser is wrapped by the ValloyParser
    //so if a file has changed via the Open Valloy or Save Valloy command
    //we need to reset the ValloyParser so it can initialized a new Converter object
    private boolean CanRunStringParser()
    {
        if( _OpenedFileName.length() <= 0)
            return false;

        if (_valloyParser == null || ValloyFilehasChanged == true)
        {
           _valloyParser = new ValloyParser(_OpenedFileName);
           ValloyFilehasChanged = false;
        }

        return true;
    }

    //Opens a file into Valloy Text Area
    public void OpenFileLocal(javax.swing.JTextArea ValloyTextArea)
    {
        //Create a file chooser
        JFileChooser fc = new JFileChooser();//In response to a button click:
        VLSFileFilter ffilter = new VLSFileFilter();
        fc.setFileFilter(ffilter);
        if( _CurrentDirValloyFilePath != null)        {
         fc.setCurrentDirectory(_CurrentDirValloyFilePath);
        }
        int returnVal = fc.showOpenDialog(fc);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
                File filename = fc.getSelectedFile();
                try{
                    if( filename != null )                    {
                        _CurrentDirValloyFilePath = fc.getCurrentDirectory();
                        _OpenedFileName = filename.toString();
                        FileReader inin = new FileReader(filename);
                        ValloyTextArea.read(inin, filename.toString());
                        ValloyFilehasChanged = true;
                    }
                }
                catch(java.io.IOException ex){
                        _ErrorData = "Cannot read from file!";
                        System.out.println("Cannot read from file!");
                }

        }
    }

    //Selects a file to open into Valloy panel
    //TODO:  Open a normal Dialog box that allows you to select a file name
    //instead of using the dialog box at alloy Analyzer.
    public  void OpenValloyFile(javax.swing.JTextArea ValloyTextArea,
            SimpleGUI pParent )
    {
        _ErrorData = "";
                
        if(pParent != null)
            asguiParent = pParent;

        OpenFileLocal(ValloyTextArea);



    }
    // Export to the alloy analyzer convertion and we tranfer it
    //directly to Alloy so it can be run.  One of the easy way to do this
    //is by writting the conversion into a temp file, passing the file name to alloy
    //and then opening the file automatically form within alloy anlayzer

    public void ExportToAlloy(javax.swing.JTextArea AlloyTextArea)
    {
        if( asguiParent != null)
        {
            File afile;
            boolean result;           
            if ( AlloyTextArea.getText().length() > 0) // if user click on Open button
            {
               try{
                   //we are saving the data into a file so we can then try to call the
                   //Alloy application
                    afile = new File(_DefaultTransferFileName);
                    result = afile.createNewFile();
                    //String fullfilePath = afile.getPath();

                    FileWriter fWriter = new FileWriter ( afile ) ; // create an instance of FileWriter
                    BufferedWriter writer = new BufferedWriter ( fWriter ) ; // create an instance of BufferedWriter
                    String writeString = AlloyTextArea.getText () ; // String object to keep the string to write

                    writer.write ( writeString , 0 , writeString.length ( ) ) ; // write the content of text area into the file. Really simple huh ...
                    writer.close ( ) ; // close the stream

                    asguiParent.doTrasferedFromValloyConverter(afile);
                }
                catch(IOException exception){
                    System.out.println ("Error processing file: " + exception);
                }
            }
        }
    }

    //Saved parsed data displayed in the Alloy Text Area into a file
    //TODO: default to only .als extensions
     public void SaveAlloyData(javax.swing.JTextArea jtextArea, javax.swing.JLabel jLabelSaveAlloyFiileName)
    {
         JFileChooser chooser = new JFileChooser () ;
       //  AlloyFileFilter ffilter = new AlloyFileFilter();
       //  chooser.setFileFilter(ffilter);
        if( _CurrentDirAlloyFilePath != null)        {
         chooser.setCurrentDirectory(_CurrentDirAlloyFilePath);
        }
           int retVal = chooser.showSaveDialog(chooser); // show the open file dialog
            if ( retVal == JFileChooser.APPROVE_OPTION ) // if user click on Open button
            {
            // start writing to the file
                try{
                    File selectedfile = chooser.getSelectedFile();
                     _CurrentDirAlloyFilePath = chooser.getCurrentDirectory();
                    FileWriter fWriter = new FileWriter ( selectedfile ) ; // create an instance of FileWriter
                    BufferedWriter writer = new BufferedWriter ( fWriter ) ; // create an instance of BufferedWriter
                    String writeString = jtextArea.getText () ; // String object to keep the string to write

                    writer.write ( writeString , 0 , writeString.length ( ) ) ; // write the content of text area into the file. Really simple huh ...
                    writer.close ( ) ; // close the stream
                    jLabelSaveAlloyFiileName.setText(selectedfile.toString());

                }
                catch(IOException exception){
                    System.out.println ("Error processing file: " + exception);
                    jLabelSaveAlloyFiileName.setText("Error processing file: " + exception.toString());
                }
            }
    }

     //Saved parsed data displayed in the Alloy Text Area into a file
     //NOTE: This code is is pretty much the same code as of the Alloy data
     public void SaveValloyData(javax.swing.JTextArea jtextArea,
            SimpleGUI pParent )
     {
          _ErrorData = "";
           JFileChooser chooser = new JFileChooser () ;
        if( _CurrentDirValloyFilePath != null)        {
         chooser.setCurrentDirectory(_CurrentDirValloyFilePath);
        }
           int retVal = chooser.showSaveDialog(chooser); // show the open file dialog
            if ( retVal == JFileChooser.APPROVE_OPTION ) // if user click on Open button
            {
            // start writing to the file
                try{
                    File thefile = chooser.getSelectedFile ();

                    _CurrentDirValloyFilePath = chooser.getCurrentDirectory();
                    FileWriter fWriter = new FileWriter ( thefile ) ; // create an instance of FileWriter
                    BufferedWriter writer = new BufferedWriter ( fWriter ) ; // create an instance of BufferedWriter
                    String writeString = jtextArea.getText () ; // String object to keep the string to write

                    writer.write ( writeString , 0 , writeString.length ( ) ) ; // write the content of text area into the file. Really simple huh ...
                    writer.close ( ) ; // close the stream
                    if(pParent != null && asguiParent == null)
                     {
                            asguiParent = pParent;
                            
                     }
                    _OpenedFileName = thefile.toString();
                    ValloyFilehasChanged = true;
                    
                    
                }
                catch(IOException exception){
                    _ErrorData = ("Error processing file: " + exception);
                    System.out.println ("Error processing file: " + exception);
                }
            }
    }

    //TODO
    //RMV: A command indicating tha Valloy is being close
    static public void ExitValloy()
    {

    }
    
}

    //Please add the input commands relevant to }
